package org.meetunexpectedly.controller;

import org.meetunexpectedly.config.LocalCache;
import org.meetunexpectedly.config.QiNiuConfig;
import org.meetunexpectedly.entity.setting.Setting;
import org.meetunexpectedly.entity.video.File;
import org.meetunexpectedly.entity.vo.Result;
import org.meetunexpectedly.holder.UserHolder;
import org.meetunexpectedly.service.file.FileService;
import org.meetunexpectedly.service.setting.SettingService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description: 文件请求控制类
 * @Author: pupil
 * @Date: 2024/08/28 下午 3:40
 */
@RestController
@RequestMapping("/meetunexpectedly/file")
public class FileController implements InitializingBean{


    @Autowired
    private FileService fileService;

    @Autowired
    private QiNiuConfig qiNiuConfig;

    @Autowired
    private SettingService settingService;

    /**
     * 获取文件上传token
     *
     * @return
     */
    @GetMapping("/getToken")
    public Result getToken(){
        return Result.ok().data(qiNiuConfig.uploadToken());
    }

    /**
     * 保存到文件表
     * @param fileKey 文件名称
     * @return
     */
    @PostMapping
    public Result save(String fileKey){
        return Result.ok().data(fileService.save(fileKey, UserHolder.get()));
    }

    /**
     * 查看文件
     * @param fileId
     * @param response
     */
    @GetMapping("/{fileId}")
    public void getFile(@PathVariable Long fileId, HttpServletResponse response) throws IOException {
        // 可以优化，如果不是指定ip调用的该接口，则不返回
        File file =  fileService.getFileTrustUrl(fileId);
        response.setContentType(file.getType());
        response.sendRedirect(file.getFileKey());
    }

    @PostMapping("/auth")
    public void auth(@RequestParam(required = false) String uuid, HttpServletResponse response) throws IOException {
        if (uuid == null || LocalCache.containsKey(uuid) == null){
            response.sendError(401);
        }else {
            LocalCache.remove(uuid);
            response.sendError(200);
        }
    }



    @Override
    public void afterPropertiesSet() throws Exception {
        final Setting setting = settingService.list(null).get(0);
        for (String s : setting.getAllowIp().split(",")) {
            LocalCache.put(s,true);
        }
    }
}
